import tkinter as tk
from tkinter import ttk
import mysql.connector

def fetch_tree_data():
    connection = None
    try:
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='jfsh1212',
            database='woodland'
        )
        cursor = connection.cursor()
        cursor.execute("SELECT tree_name FROM binary_fang ")
        tree_names = [row[0] for row in cursor.fetchall()]
        return tree_names
    except mysql.connector.Error as err:
        print(f"连接错误: {err}")
        return []
    finally:
        if connection and connection.is_connected():
            connection.close()

def fetch_province_data():
    connection = None
    try:
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='jfsh1212',
            database='woodland'
        )
        cursor = connection.cursor()
        cursor.execute("SELECT id, sheng FROM province")
        provinces = cursor.fetchall()
        return {row[1]: row[0] for row in provinces}
    except mysql.connector.Error as err:
        print(f"连接错误: {err}")
        return []
    finally:
        if connection and connection.is_connected():
            connection.close()

def fetch_city_data(province_id):
    connection = None
    try:
        connection = mysql.connector.connect(
            host='localhost',
            user='root',
            password='jfsh1212',
            database='woodland'
        )
        cursor = connection.cursor()
        cursor.execute("SELECT shi FROM city WHERE province_id = %s", (province_id,))
        cities = [row[0] for row in cursor.fetchall()]
        return cities
    except mysql.connector.Error as err:
        print(f"连接错误: {err}")
        return []
    finally:
        if connection and connection.is_connected():
            connection.close()

# 实例化窗体对象
root = tk.Tk()

# 设置窗口
root.geometry("1400x600+150+150")
root.title("林地碳汇计算器")
root.attributes("-alpha", 0.9)
root["background"] = "#ffffff"


# 创建一个 StringVar 用于存储树种选择
tree_options = fetch_tree_data()
tree_var = tk.StringVar(root)
tree_var.set(tree_options[0] if tree_options else "")  # 默认选择第一个树种

# 标签和树种下拉菜单
tk.Label(root, text="选择树种", bg="#ffffff", font=("Arial", 12)).grid(row=0, column=0, padx=10, pady=5, sticky="w")
tree_menu = ttk.Combobox(root, textvariable=tree_var, values=tree_options, state="readonly")
tree_menu.grid(row=1, column=0, padx=10, pady=10, sticky="w")

# cunchu shengfen
sheng_data = fetch_province_data()
sheng_var = tk.StringVar(root)
first_province = next(iter(sheng_data), "")  # 获取第一个省份的名称
sheng_var.set(first_province)  # 默认选择第一个省份


# Province selection
tk.Label(root, text="选择省份", bg="#ffffff", font=("Arial", 12)).grid(row=0, column=1, padx=10, pady=5, sticky="w")
sheng_menu = ttk.Combobox(root, textvariable=sheng_var, state="readonly", values=list(sheng_data.keys()))
sheng_menu.grid(row=1, column=1, padx=10, pady=10, sticky="w")

#cunchu shi
# shi_options = fetch_city_data()
shi_var = tk.StringVar(root)
shi_var.set("")
# shi_var.set(shi_options[0] if shi_options else "")

#xuanze shi
tk.Label(root,text="选择城市",bg="#ffffff",font=("Arial", 12 )).grid(row=0, column=2, padx=10, pady=5, sticky="w")
shi_menu = ttk.Combobox(root, textvariable=shi_var, state="readonly")
shi_menu.grid(row=1, column=2, padx=10, pady=10, sticky="w")

def update_area_options(event):
    selected_tree = tree_var.get()
    area_options = fetch_area_data(selected_tree)
    area_menu['values'] = area_options
    area_menu.set(area_options[0] if area_options else "")  # 默认选择第一个区域

def update_city_options(event):
    selected_province = sheng_var.get()
    province_id = sheng_data[selected_province]  # 获取选中省份的ID
    city_options = fetch_city_data(province_id)
    shi_menu['values'] = city_options
    shi_var.set(city_options[0] if city_options else "")  # 默认选择第一个城市

tree_menu.bind("<<ComboboxSelected>>", update_area_options)
sheng_menu.bind("<<ComboboxSelected>>", update_city_options)

# 输入框及计算逻辑
def on_entry_click(event):
    if event.widget.get() == event.widget.placeholder:
        event.widget.delete(0, tk.END)
        event.widget.config(fg='black')

def on_focusout(event):
    if event.widget.get() == '':
        event.widget.insert(0, event.widget.placeholder)
        event.widget.config(fg='grey')

def calculate():
    selected_tree = tree_var.get()
    diameter = diameter_entry.get()
    height = height_entry.get()
    quantity = quantity_entry.get()
    try:
        diameter = float(diameter)
        height = float(height)
        quantity = int(quantity)
    except ValueError:
        result_var.set("请输入有效的树径、树高和数量")
        return

    # 杨树二元生物量因子模型参数
    c0 = 0.75347
    c1 = 0.25371
    c2 = -0.35596
    biomass = c0 * (diameter ** c1) * (height ** c2)

    # 杨树相容性李木材积模型参数
    d0 = 0.00006114
    d1 = 1.89521
    d2 = 0.94759
    volume = d0 * (diameter ** d1) * (height ** d2)

    # 计算杨树干材生物量
    dry_biomass = biomass * volume * quantity

    # 杨树干皮、树枝、树叶比例模型
    g1 = 0.64735 * (height ** -0.36906)
    g2 = 1.13607 * (diameter ** 0.72356) * (height ** -1.13102)
    g3 = 1.03548 * (height ** -1.05634)

    # 计算杨树地上生物量
    above_ground_biomass = dry_biomass * (1 + g1 + g2 + g3)

    # 计算杨树碳库量
    carbon_storage = (dry_biomass * (0.4758 + g1 * 0.4679 + g2 * 0.4723))

    # 杨树二元根茎比模型参数
    e0 = 0.5081
    e1 = 0.1860
    e2 = -0.5065
    rsr = e0 * (diameter ** e1) * (height ** e2)

    # 计算杨树地下生物量
    below_ground_biomass = dry_biomass * rsr

    # 计算杨树地下碳库
    below_ground_carbon_storage = (biomass * volume * rsr * 0.4644)

    # 计算杨树全树生物量
    total_biomass = above_ground_biomass + below_ground_biomass

    # 计算杨树重复树的生物量
    total_biomass_repeated = total_biomass * quantity

    # 计算杨树全树碳库量
    total_carbon_storage = carbon_storage + below_ground_carbon_storage

    # 计算杨树总碳库量
    total_carbon_storage_all = total_carbon_storage * quantity

    # 计算杨树碳汇
    annual_growth_rate = 0.0316
    carbon_sinks = total_carbon_storage_all * annual_growth_rate

    # 计算杨树总碳汇
    total_carbon_sinks = quantity * carbon_sinks

    # 显示计算结果
    result = (f"树种: {selected_tree}\n"
              # f"地区: {selected_area}\n"
              f"树径: {diameter} cm\n"
              f"树高: {height} cm\n"
              f"数量: {quantity}\n"
              f"干材生物量: {dry_biomass:.4f} t\n"
              f"全树生物量: {total_biomass:.4f} t\n"
              f"重复树的生物量: {total_biomass_repeated:.4f} t\n"
              f"碳库量: {carbon_storage:.4f} tC\n"
              f"总碳库量: {total_carbon_storage_all:.4f} tC\n"
              f"碳汇: {carbon_sinks:.4f} tC\n"
              f"总碳汇: {total_carbon_sinks:.4f} tC")
    result_var.set(result)


# 树径输入框
tk.Label(root, text="树径 (cm)", bg="#ffffff", font=("Arial", 12)).grid(row=0, column=3, padx=10, pady=5, sticky="w")
diameter_entry = tk.Entry(root)
diameter_entry.placeholder = "请输入树径(cm)"
diameter_entry.insert(0, diameter_entry.placeholder)
diameter_entry.config(fg='grey')
diameter_entry.bind("<FocusIn>", on_entry_click)
diameter_entry.bind("<FocusOut>", on_focusout)
diameter_entry.grid(row=1, column=3, padx=10, pady=10, sticky="w")

# 树高输入框
tk.Label(root, text="树高 (cm)", bg="#ffffff", font=("Arial", 12)).grid(row=0, column=4, padx=10, pady=5, sticky="w")
height_entry = tk.Entry(root)
height_entry.placeholder = "请输入树高(cm)"
height_entry.insert(0, height_entry.placeholder)
height_entry.config(fg='grey')
height_entry.bind("<FocusIn>", on_entry_click)
height_entry.bind("<FocusOut>", on_focusout)
height_entry.grid(row=1, column=4, padx=10, pady=10, sticky="w")

# 数量输入框
tk.Label(root, text="数量", bg="#ffffff", font=("Arial", 12)).grid(row=0, column=5, padx=10, pady=5, sticky="w")
quantity_entry = tk.Entry(root)
quantity_entry.placeholder = "请输入树的数量"
quantity_entry.insert(0, quantity_entry.placeholder)
quantity_entry.config(fg='grey')
quantity_entry.bind("<FocusIn>", on_entry_click)
quantity_entry.bind("<FocusOut>", on_focusout)
quantity_entry.grid(row=1, column=5, padx=10, pady=10, sticky="w")

# 计算结果显示
tk.Label(root, text="计算结果显示", bg="#ffffff", font=("Arial", 12)).grid(row=0, column=6, padx=10, pady=5, sticky="w")
result_var = tk.StringVar()
result_label = tk.Label(root, textvariable=result_var, bg="#ffffff", font=("Arial", 12), anchor="w", justify="left")
result_label.grid(row=1, column=6, padx=10, pady=10, sticky="w")

# 计算按钮
calculate_button = tk.Button(root, text="计   算", command=calculate, font=("Arial", 12), width=10, height=1)
calculate_button.grid(row=4, column=0, columnspan=6, pady=20)

# 启动事件循环
root.mainloop()
